const fs = require('fs');
const path = require('path');

// 读取配置
const config = JSON.parse(fs.readFileSync('config.json', 'utf8'));

console.log('开始执行文档清理...');

// 创建归档目录
const archivePath = path.join(config.paths.docsRoot, 'archive');
const timestamp = new Date().toISOString().split('T')[0];

if (!fs.existsSync(archivePath)) {
    fs.mkdirSync(archivePath, { recursive: true });
    console.log('创建归档目录:', archivePath);
}

const outdatedPath = path.join(archivePath, 'outdated-docs', timestamp);
if (!fs.existsSync(outdatedPath)) {
    fs.mkdirSync(outdatedPath, { recursive: true });
    console.log('创建过时文档目录:', outdatedPath);
}

const completedPath = path.join(archivePath, 'completed-projects');
if (!fs.existsSync(completedPath)) {
    fs.mkdirSync(completedPath, { recursive: true });
    console.log('创建完成项目目录:', completedPath);
}

// 归档过时文件
const outdatedFiles = config.cleanup.deleteFiles;
let archivedCount = 0;

for (const fileName of outdatedFiles) {
    const filePath = path.join(config.paths.docsRoot, fileName);
    
    if (fs.existsSync(filePath)) {
        const archiveFilePath = path.join(outdatedPath, fileName);
        try {
            fs.copyFileSync(filePath, archiveFilePath);
            fs.unlinkSync(filePath);
            console.log('归档过时文件:', fileName);
            archivedCount++;
        } catch (error) {
            console.error('归档文件失败:', fileName, error.message);
        }
    } else {
        console.log('文件不存在，跳过:', fileName);
    }
}

// 归档完成的项目目录
const projectsToArchive = config.cleanup.archiveDirectories;
let projectsArchivedCount = 0;

function copyDirectoryRecursive(source, target) {
    if (!fs.existsSync(target)) {
        fs.mkdirSync(target, { recursive: true });
    }
    
    const items = fs.readdirSync(source);
    
    for (const item of items) {
        const sourcePath = path.join(source, item);
        const targetPath = path.join(target, item);
        
        if (fs.statSync(sourcePath).isDirectory()) {
            copyDirectoryRecursive(sourcePath, targetPath);
        } else {
            fs.copyFileSync(sourcePath, targetPath);
        }
    }
}

function removeDirectoryRecursive(dirPath) {
    if (fs.existsSync(dirPath)) {
        const items = fs.readdirSync(dirPath);
        
        for (const item of items) {
            const itemPath = path.join(dirPath, item);
            
            if (fs.statSync(itemPath).isDirectory()) {
                removeDirectoryRecursive(itemPath);
            } else {
                fs.unlinkSync(itemPath);
            }
        }
        
        fs.rmdirSync(dirPath);
    }
}

for (const projectDir of projectsToArchive) {
    const sourcePath = path.join(config.paths.docsRoot, projectDir);
    const targetPath = path.join(completedPath, projectDir);
    
    if (fs.existsSync(sourcePath)) {
        try {
            copyDirectoryRecursive(sourcePath, targetPath);
            removeDirectoryRecursive(sourcePath);
            console.log('归档项目目录:', projectDir);
            projectsArchivedCount++;
        } catch (error) {
            console.error('归档项目目录失败:', projectDir, error.message);
        }
    } else {
        console.log('目录不存在，跳过:', projectDir);
    }
}

// 生成清理报告
const report = {
    timestamp: new Date().toISOString(),
    summary: {
        archivedFiles: archivedCount,
        archivedProjects: projectsArchivedCount,
        totalOperations: archivedCount + projectsArchivedCount
    },
    operations: {
        archivedFiles: outdatedFiles.filter(f => fs.existsSync(path.join(outdatedPath, f))),
        archivedProjects: projectsToArchive.filter(p => fs.existsSync(path.join(completedPath, p)))
    }
};

fs.writeFileSync('validation/cleanup-report.json', JSON.stringify(report, null, 2));

// 生成可读报告
let summary = `# 文档清理执行报告\n\n`;
summary += `执行时间: ${report.timestamp}\n\n`;
summary += `## 执行概要\n\n`;
summary += `- 归档文件数: ${report.summary.archivedFiles}\n`;
summary += `- 归档项目数: ${report.summary.archivedProjects}\n`;
summary += `- 总操作数: ${report.summary.totalOperations}\n\n`;

if (report.operations.archivedFiles.length > 0) {
    summary += `## 归档的过时文件\n\n`;
    report.operations.archivedFiles.forEach(file => {
        summary += `- ${file}\n`;
    });
    summary += `\n`;
}

if (report.operations.archivedProjects.length > 0) {
    summary += `## 归档的项目目录\n\n`;
    report.operations.archivedProjects.forEach(project => {
        summary += `- ${project}\n`;
    });
    summary += `\n`;
}

summary += `## 新的目录结构\n\n`;
summary += `清理后的docs目录更加整洁，过时文件已归档到 \`archive/outdated-docs/${timestamp}/\`，完成的项目已归档到 \`archive/completed-projects/\`。\n\n`;

fs.writeFileSync('validation/cleanup-summary.md', summary);

console.log('\n=== 清理完成 ===');
console.log(`归档文件数: ${report.summary.archivedFiles}`);
console.log(`归档项目数: ${report.summary.archivedProjects}`);
console.log(`总操作数: ${report.summary.totalOperations}`);
console.log('\n清理报告已生成:');
console.log('- validation/cleanup-report.json');
console.log('- validation/cleanup-summary.md');